class MainWindow {
    constructor() {
        this.init();
    }

    init() {
        this.loadWindowSettings();
        this.loadNovelData();
        this.bindEvents();
    }

    bindEvents() {
        // 窗口设置相关事件
        document.getElementById('windowWidth').addEventListener('input', this.validateWindowInput.bind(this));
        document.getElementById('windowHeight').addEventListener('input', this.validateWindowInput.bind(this));
        document.getElementById('windowX').addEventListener('input', this.validateWindowInput.bind(this));
        document.getElementById('windowY').addEventListener('input', this.validateWindowInput.bind(this));
        
        // 拖拽文件功能
        this.initDragAndDrop();
        
        // 章节搜索实时功能
        this.initChapterSearch();
    }

    initChapterSearch() {
        const chapterSearch = document.getElementById('chapterSearch');
        if (chapterSearch) {
            let searchTimeout;
            chapterSearch.addEventListener('input', (e) => {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => {
                    if (e.target.value.trim()) {
                        searchChapter();
                    }
                }, 500); // 500ms延迟，避免频繁搜索
            });
        }
    }

    initDragAndDrop() {
        const dropZone = document.getElementById('dropZone');
        
        dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropZone.style.borderColor = '#667eea';
            dropZone.style.backgroundColor = '#f0f4ff';
        });
        
        dropZone.addEventListener('dragleave', (e) => {
            e.preventDefault();
            dropZone.style.borderColor = '#ddd';
            dropZone.style.backgroundColor = 'transparent';
        });
        
        dropZone.addEventListener('drop', async (e) => {
            e.preventDefault();
            dropZone.style.borderColor = '#ddd';
            dropZone.style.backgroundColor = 'transparent';
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                const file = files[0];
                if (file.type === 'text/plain' || file.name.endsWith('.txt')) {
                    try {
                        const content = await this.readFileContent(file);
                        const fileName = file.name.replace('.txt', '');
                        
                        // 显示文件信息
                        document.getElementById('fileInfo').style.display = 'block';
                        document.getElementById('fileName').textContent = fileName;
                        document.getElementById('fileSize').textContent = `文件大小: ${(content.length / 1024).toFixed(2)} KB`;
                        
                        // 自动填充内容
                        document.getElementById('novelTitle').value = fileName;
                        document.getElementById('novelContent').value = content;
                        
                        this.showStatus(`已拖拽导入文件: ${fileName}`, 'success');
                    } catch (error) {
                        console.error('读取拖拽文件失败:', error);
                        this.showStatus('读取文件失败', 'error');
                    }
                } else {
                    this.showStatus('请拖拽TXT文件', 'error');
                }
            }
        });
    }

    readFileContent(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (e) => resolve(e.target.result);
            reader.onerror = (e) => reject(e);
            reader.readAsText(file, 'utf-8');
        });
    }

    validateWindowInput(event) {
        const value = parseInt(event.target.value);
        const min = parseInt(event.target.min);
        const max = parseInt(event.target.max);
        
        if (value < min) {
            event.target.value = min;
        } else if (value > max) {
            event.target.value = max;
        }
    }

    async loadWindowSettings() {
        try {
            const config = await window.electronAPI.ipcRenderer.invoke('get-floating-config');
            document.getElementById('windowWidth').value = config.width;
            document.getElementById('windowHeight').value = config.height;
            document.getElementById('windowX').value = config.x;
            document.getElementById('windowY').value = config.y;
        } catch (error) {
            console.error('加载窗口设置失败:', error);
        }
    }

    async loadNovelData() {
        try {
            const novelData = await window.electronAPI.ipcRenderer.invoke('get-novel-content');
            document.getElementById('novelTitle').value = novelData.title || '';
            document.getElementById('novelContent').value = novelData.content || '';
            this.loadNovelList();
        } catch (error) {
            console.error('加载小说数据失败:', error);
        }
    }

    loadNovelList() {
        const novelList = document.getElementById('novelList');
        const savedNovels = this.getSavedNovels();
        
        if (savedNovels.length === 0) {
            novelList.innerHTML = '<div class="novel-item" style="text-align: center; color: #999; padding: 20px;">暂无保存的小说</div>';
            return;
        }
        
        novelList.innerHTML = savedNovels.map(novel => `
            <div class="novel-item" data-title="${novel.title}">
                <div style="font-weight: bold; color: #667eea;">${novel.title}</div>
                <div style="font-size: 0.9em; color: #666; margin-top: 3px;">
                    字数: ${novel.content.length} | 保存时间: ${novel.saveTime}
                </div>
            </div>
        `).join('');
        
        // 绑定点击事件
        novelList.querySelectorAll('.novel-item').forEach(item => {
            item.addEventListener('click', () => {
                const title = item.dataset.title;
                this.loadNovelByTitle(title);
            });
        });
    }

    getSavedNovels() {
        const novels = [];
        for (let i = 0; i < localStorage.length; i++) {
            const key = localStorage.key(i);
            if (key.startsWith('novel_')) {
                try {
                    const novelData = JSON.parse(localStorage.getItem(key));
                    novels.push(novelData);
                } catch (e) {
                    console.error('解析小说数据失败:', e);
                }
            }
        }
        return novels.sort((a, b) => new Date(b.saveTime) - new Date(a.saveTime));
    }

    loadNovelByTitle(title) {
        const novelData = localStorage.getItem(`novel_${title}`);
        if (novelData) {
            const novel = JSON.parse(novelData);
            document.getElementById('novelTitle').value = novel.title;
            document.getElementById('novelContent').value = novel.content;
            this.showStatus(`已加载小说: ${novel.title}`, 'success');
        }
    }

    showStatus(message, type = 'success') {
        // 创建状态消息
        const statusDiv = document.createElement('div');
        statusDiv.className = `status ${type}`;
        statusDiv.textContent = message;
        
        // 插入到第一个卡片后面
        const firstCard = document.querySelector('.card');
        firstCard.parentNode.insertBefore(statusDiv, firstCard.nextSibling);
        
        // 3秒后自动移除
        setTimeout(() => {
            if (statusDiv.parentNode) {
                statusDiv.parentNode.removeChild(statusDiv);
            }
        }, 3000);
    }
}

// 全局函数，供HTML按钮调用
window.applyWindowSettings = async function() {
    try {
        const config = {
            width: parseInt(document.getElementById('windowWidth').value),
            height: parseInt(document.getElementById('windowHeight').value),
            x: parseInt(document.getElementById('windowX').value),
            y: parseInt(document.getElementById('windowY').value)
        };
        
        await window.electronAPI.ipcRenderer.invoke('update-floating-config', config);
        mainWindow.showStatus('窗口设置已应用', 'success');
    } catch (error) {
        console.error('应用窗口设置失败:', error);
        mainWindow.showStatus('应用设置失败', 'error');
    }
};

window.resetWindowSettings = function() {
    document.getElementById('windowWidth').value = 400;
    document.getElementById('windowHeight').value = 300;
    document.getElementById('windowX').value = 100;
    document.getElementById('windowY').value = 100;
    mainWindow.showStatus('已重置为默认设置', 'success');
};

window.saveNovel = async function() {
    try {
        const title = document.getElementById('novelTitle').value.trim();
        const content = document.getElementById('novelContent').value.trim();
        
        if (!title || !content) {
            mainWindow.showStatus('请填写小说标题和内容', 'error');
            return;
        }
        
        // 保存到本地存储
        const novelData = { 
            title, 
            content,
            saveTime: new Date().toLocaleString('zh-CN')
        };
        
        // 保存到小说列表
        localStorage.setItem(`novel_${title}`, JSON.stringify(novelData));
        
        // 保存当前小说
        localStorage.setItem('currentNovel', JSON.stringify(novelData));
        
        // 通知悬浮窗更新内容
        await window.electronAPI.ipcRenderer.invoke('update-novel-content', novelData);
        
        // 刷新小说列表
        mainWindow.loadNovelList();
        
        mainWindow.showStatus('小说已保存', 'success');
    } catch (error) {
        console.error('保存小说失败:', error);
        mainWindow.showStatus('保存失败', 'error');
    }
};

window.loadNovel = function() {
    try {
        const savedNovel = localStorage.getItem('currentNovel');
        if (savedNovel) {
            const novelData = JSON.parse(savedNovel);
            document.getElementById('novelTitle').value = novelData.title;
            document.getElementById('novelContent').value = novelData.content;
            mainWindow.showStatus('小说已加载', 'success');
        } else {
            mainWindow.showStatus('没有找到保存的小说', 'error');
        }
    } catch (error) {
        console.error('加载小说失败:', error);
        mainWindow.showStatus('加载失败', 'error');
    }
};

window.clearNovel = function() {
    if (confirm('确定要清空小说内容吗？')) {
        document.getElementById('novelTitle').value = '';
        document.getElementById('novelContent').value = '';
        mainWindow.showStatus('内容已清空', 'success');
    }
};

window.deleteNovel = function() {
    const title = document.getElementById('novelTitle').value.trim();
    if (!title) {
        mainWindow.showStatus('请先选择要删除的小说', 'error');
        return;
    }
    
    if (confirm(`确定要删除小说"${title}"吗？`)) {
        localStorage.removeItem(`novel_${title}`);
        document.getElementById('novelTitle').value = '';
        document.getElementById('novelContent').value = '';
        mainWindow.loadNovelList();
        mainWindow.showStatus('小说已删除', 'success');
    }
};

window.browseTxtFile = async function() {
    try {
        const result = await window.electronAPI.ipcRenderer.invoke('import-txt-file');
        
        if (result.success) {
            // 显示文件信息
            document.getElementById('fileInfo').style.display = 'block';
            document.getElementById('fileName').textContent = result.title;
            document.getElementById('fileSize').textContent = `文件大小: ${(result.content.length / 1024).toFixed(2)} KB`;
            
            // 自动填充内容
            document.getElementById('novelTitle').value = result.title;
            document.getElementById('novelContent').value = result.content;
            
            mainWindow.showStatus(`已选择文件: ${result.title}`, 'success');
        } else if (result.message !== '未选择文件') {
            mainWindow.showStatus(result.message, 'error');
        }
    } catch (error) {
        console.error('浏览文件失败:', error);
        mainWindow.showStatus('浏览文件失败', 'error');
    }
};

window.importTxtFile = async function() {
    const title = document.getElementById('novelTitle').value.trim();
    const content = document.getElementById('novelContent').value.trim();
    
    if (!title || !content) {
        mainWindow.showStatus('请先选择或输入小说内容', 'error');
        return;
    }
    
    try {
        // 自动保存到悬浮窗
        const novelData = { 
            title: title, 
            content: content,
            saveTime: new Date().toLocaleString('zh-CN')
        };
        
        // 保存到小说列表
        localStorage.setItem(`novel_${title}`, JSON.stringify(novelData));
        
        // 保存当前小说
        localStorage.setItem('currentNovel', JSON.stringify(novelData));
        
        await ipcRenderer.invoke('update-novel-content', novelData);
        
        // 刷新小说列表
        mainWindow.loadNovelList();
        
        // 隐藏文件信息
        document.getElementById('fileInfo').style.display = 'none';
        
        // 显示章节定位功能
        document.getElementById('chapterSection').style.display = 'block';
        
        mainWindow.showStatus(`成功导入并保存: ${title}`, 'success');
    } catch (error) {
        console.error('导入TXT文件失败:', error);
        mainWindow.showStatus('导入失败', 'error');
    }
};

window.searchChapter = function() {
    const content = document.getElementById('novelContent').value;
    const searchTerm = document.getElementById('chapterSearch').value.trim();
    
    if (!content) {
        mainWindow.showStatus('请先导入小说内容', 'error');
        return;
    }
    
    // 章节匹配模式（支持更多格式）
    const chapterPatterns = [
        /^第[一二三四五六七八九十百千万\d]+章\s*[^\n]*/gm,
        /^第[一二三四五六七八九十百千万\d]+节\s*[^\n]*/gm,
        /^[一二三四五六七八九十百千万\d]+、\s*[^\n]*/gm,
        /^[一二三四五六七八九十百千万\d]+\.\s*[^\n]*/gm,
        /^第[一二三四五六七八九十百千万\d]+回\s*[^\n]*/gm,
        /^[一二三四五六七八九十百千万\d]+[章节回]\s*[^\n]*/gm,
        /^[A-Za-z]+[一二三四五六七八九十百千万\d]+\s*[^\n]*/gm
    ];
    
    const lines = content.split('\n');
    const chapters = [];
    
    lines.forEach((line, index) => {
        const trimmedLine = line.trim();
        for (const pattern of chapterPatterns) {
            if (pattern.test(trimmedLine)) {
                const chapterTitle = trimmedLine;
                if (!searchTerm || chapterTitle.toLowerCase().includes(searchTerm.toLowerCase())) {
                    chapters.push({
                        title: chapterTitle,
                        lineNumber: index + 1,
                        position: index
                    });
                }
                break;
            }
        }
    });
    
    // 显示章节列表
    const chapterList = document.getElementById('chapterList');
    if (chapters.length === 0) {
        chapterList.innerHTML = '<div style="text-align: center; color: #999;">未找到章节</div>';
        return;
    }
    
    // 限制显示数量，避免界面卡顿
    const displayChapters = chapters.slice(0, 100);
    const hasMore = chapters.length > 100;
    
    chapterList.innerHTML = displayChapters.map(chapter => `
        <div class="chapter-item" style="padding: 8px; border-bottom: 1px solid #e1e5e9; cursor: pointer; transition: background 0.2s;" 
             onmouseover="this.style.background='#e3f2fd'" 
             onmouseout="this.style.background='transparent'"
             onclick="goToChapter(${chapter.position})">
            <div style="font-weight: bold; color: #667eea;">${chapter.title}</div>
            <div style="font-size: 0.9em; color: #666;">第 ${chapter.lineNumber} 行</div>
        </div>
    `).join('') + (hasMore ? `<div style="text-align: center; color: #999; padding: 8px;">... 还有 ${chapters.length - 100} 个章节未显示</div>` : '');
    
    mainWindow.showStatus(`找到 ${chapters.length} 个章节${hasMore ? '（显示前100个）' : ''}`, 'success');
};

window.goToChapter = function(position) {
    const content = document.getElementById('novelContent');
    const lines = content.value.split('\n');
    
    // 计算目标位置
    let targetPosition = 0;
    for (let i = 0; i < position; i++) {
        targetPosition += lines[i].length + 1; // +1 for newline
    }
    
    // 滚动到目标位置
    content.focus();
    content.setSelectionRange(targetPosition, targetPosition);
    
    // 滚动到可见区域
    const lineHeight = 20; // 估算行高
    const visibleLines = Math.floor(content.clientHeight / lineHeight);
    const targetLine = position;
    const scrollTop = Math.max(0, (targetLine - visibleLines / 2) * lineHeight);
    content.scrollTop = scrollTop;
    
    mainWindow.showStatus('已定位到章节', 'success');
};

window.clearFileInput = function() {
    document.getElementById('txtFileInput').value = '';
    document.getElementById('fileInfo').style.display = 'none';
    document.getElementById('novelTitle').value = '';
    document.getElementById('novelContent').value = '';
    mainWindow.showStatus('文件选择已清空', 'success');
};

window.importJianLai = async function() {
    try {
        mainWindow.showStatus('正在导入《剑来》小说，请稍候...', 'success');
        
        const result = await ipcRenderer.invoke('import-jianlai-file');
        
        if (result.success) {
            document.getElementById('novelTitle').value = result.title;
            document.getElementById('novelContent').value = result.content;
            
            // 显示文件信息
            document.getElementById('fileInfo').style.display = 'block';
            document.getElementById('fileName').textContent = result.title;
            document.getElementById('fileSize').textContent = `文件大小: ${(result.content.length / 1024 / 1024).toFixed(2)} MB | 编码: ${result.encoding}`;
            
            // 显示章节定位功能
            document.getElementById('chapterSection').style.display = 'block';
            
            mainWindow.showStatus(`成功导入《剑来》小说！共 ${result.chapterCount} 个章节`, 'success');
        } else {
            mainWindow.showStatus(result.message, 'error');
        }
    } catch (error) {
        console.error('导入《剑来》失败:', error);
        mainWindow.showStatus('导入失败', 'error');
    }
};

// 初始化主窗口
let mainWindow;
document.addEventListener('DOMContentLoaded', () => {
    mainWindow = new MainWindow();
});

// 监听来自悬浮窗的消息
ipcRenderer.on('novel-content-updated', (event, data) => {
    document.getElementById('novelTitle').value = data.title;
    document.getElementById('novelContent').value = data.content;
    mainWindow.showStatus('悬浮窗内容已更新', 'success');
});

// 监听窗口关闭事件
window.addEventListener('beforeunload', () => {
    // 保存当前设置
    const config = {
        width: parseInt(document.getElementById('windowWidth').value),
        height: parseInt(document.getElementById('windowHeight').value),
        x: parseInt(document.getElementById('windowX').value),
        y: parseInt(document.getElementById('windowY').value)
    };
    
    localStorage.setItem('windowConfig', JSON.stringify(config));
});